//
//  HXQiYeLocaleJobTableViewController.m
//  KD
//
//  Created by 梅洋 on 16/7/28.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXQiYeLocaleJobTableViewController.h"
#import "HXQiYeLocaleJobTableViewCell.h"
#import "HXQYPictureGatherViewController.h"
#import "HXQYQueryListViewController.h"
#import "HXGetCorpTaskListModel.h"
#import "HXGetAreaOrKindModel.h"

@interface HXQiYeLocaleJobTableViewController ()

@property (nonatomic,assign) NSInteger pageNum;
@property (nonatomic,strong) NSMutableArray <HXGetCorpTaskResultListModel *> * dataArray;
@property (nonatomic,strong) NSMutableArray <HXGetAreaOrKindListModel *> * areaOrKindArray;

@property (nonatomic,assign) NSString * sendTime;
@property (nonatomic,assign) BOOL isDelete;
@end

@implementation HXQiYeLocaleJobTableViewController

//懒加载
-(NSMutableArray<HXGetCorpTaskResultListModel *> *)dataArray{

    if (_dataArray == nil) {
        
        _dataArray = [[NSMutableArray alloc] init];
    }
    
    return _dataArray;
}
-(NSMutableArray <HXGetAreaOrKindListModel *> *)areaOrKindArray{

    if (_areaOrKindArray == nil) {
        
        HXGetAreaOrKindListModel * model = [[HXGetAreaOrKindListModel alloc] initWithTypeName:@"全部" withTypeValue:@"-1"];
        _areaOrKindArray = [[NSMutableArray alloc] initWithObjects:model, nil];
    }
    
    return _areaOrKindArray;
}

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.translucent = YES;
    
    //加载刷洗按钮
    [self loadCreateStupRefresh];
}

/**
 刷新按钮
 */
-(void)loadCreateStupRefresh{

    self.tableView.mj_header=[AWRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    self.tableView.mj_footer=[AWRefreshFooder footerWithRefreshingTarget:self refreshingAction:@selector(getMoreData)];
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;
    self.tableView.mj_footer.automaticallyHidden = NO;
    [self.tableView.mj_header beginRefreshing];
}

/**
 加载数据
 */
-(void)getData{

    self.pageNum = 0;
    
    [NetworkAPI getGetCorpTaskListWithPageNum:self.pageNum
                                      Success:^(HXGetCorpTaskListModel *result) {
                                          
                                          if ([result.code integerValue] == 200) {
                                              
                                              [self.dataArray removeAllObjects];
                                              self.dataArray = [result.resultlist mutableCopy];
                                              [self.tableView.mj_footer resetNoMoreData];
                                              [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
                                              [self.tableView.mj_header endRefreshing];
                                              self.pageNum ++;
                                              [self.tableView reloadData];
                                              if ([result.resultlist count] < 10) {
                                                  [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                  self.tableView.mj_footer.alpha = 1.0f;
                                                  return;
                                              }
                                          }else if ([result.code integerValue] == 400){
                                              [self.tableView.mj_header endRefreshing];
                                              [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                              self.tableView.mj_footer.alpha = 1.0f;
                                              [SVProgressHUD showErrorWithStatus:@"暂无数据"];
                                          }
                                      }
                                      failure:^(NSError *err) {
                                          [self.tableView.mj_header endRefreshing];
                                          [SVProgressHUD showErrorWithStatus:@"网络错误!"];

                                      }];
}

/**
 加载更多数据
 */
-(void)getMoreData{
    
    [NetworkAPI getGetCorpTaskListWithPageNum:self.pageNum
                                      Success:^(HXGetCorpTaskListModel *result) {
                                          if ([result.code integerValue] == 200) {
                                              if ([result.resultlist count] == 0) {
                                                  [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                  self.tableView.mj_footer.alpha = 1.0f;
                                                  return;
                                              }else if ([result.resultlist count] < 10) {
                                                  [self.dataArray addObjectsFromArray:result.resultlist];
                                                  [self.tableView reloadData];
                                                  [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                  self.tableView.mj_footer.alpha = 1.0f;
                                              }else {
                                                  self.pageNum++;
                                                  [self.dataArray addObjectsFromArray:result.resultlist];
                                                  [self.tableView reloadData];
                                                  [self.tableView.mj_footer endRefreshing];
                                                  self.tableView.mj_footer.alpha = 0;
                                              }
                                          }else if ([result.code integerValue] == 400){
                                              
                                              [self.tableView.mj_header endRefreshing];
                                              [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                              self.tableView.mj_footer.alpha = 1.0f;
                                              [SVProgressHUD showSuccessWithStatus:@"已加载全部"];
                                          }
                                      }
                                      failure:^(NSError *err) {
                                          [self.tableView.mj_footer endRefreshing];
                                          [SVProgressHUD showErrorWithStatus:@"网络错误!"];
                                      }];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [NetworkAPI getGetAreaOrKindSuccess:^(HXGetAreaOrKindModel *result) {
        
        if ([result.code integerValue] == 200) {
            
            [self.areaOrKindArray addObjectsFromArray:result.resultlist];
        }
        
    } failure:^(NSError *err) {
        
    }];
    
    self.navigationItem.title = @"任务列表";
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    //右侧的bar按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addRenWuList)];
}

/**
 添加任务列表
 */
-(void)addRenWuList{

    HXQYQueryListViewController * qyQueryVc = [[HXQYQueryListViewController alloc] init];
    
    qyQueryVc.qyLJVc = self;
    qyQueryVc.areaOrKindArray = self.areaOrKindArray;
    
    [self presentViewController:qyQueryVc animated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return 1;
}

//创建单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HXQiYeLocaleJobTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HXQiYeLocaleJobTableViewCell"];
    
    if (cell == nil) {
        
        cell = [[HXQiYeLocaleJobTableViewCell alloc] init];
        
//        cell.backgroundColor = [UIColor orangeColor];
    }
    
    cell.resultModel = self.dataArray[indexPath.section];
    
    return cell;
}
//组头视图的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 2.f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 1.f;
}

//单元格的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    CGFloat height = 60.f;
    height += [self.dataArray[indexPath.section].SiteName heightWithFont:[UIFont systemFontOfSize:15] withinWidth:HXSCREEN_WIDTH-72];
    return height;
}

//单元格的点击相应事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    HXGetCorpTaskResultListModel * model = self.dataArray[indexPath.section];
    
    HXQYPictureGatherViewController * qyVc = [[HXQYPictureGatherViewController alloc] initWithCompanyName:model.SiteName withPushType:QY_JUMP_LISTRESULT withTaskId:model.ID withSiteWorkContent:@"" withGroupName:model.GroupName];
    
    [self.navigationController pushViewController:qyVc animated:YES];
}

//删除列表任务
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HXGetCorpTaskResultListModel *data = self.dataArray[indexPath.section];
    _sendTime = data.CreateDate;
    UITableViewRowAction * deleteAtion = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self isDeleteTaskTime];
        if (_isDelete == YES) {
            [self.dataArray removeObjectAtIndex:indexPath.section];
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
            //[tableView deleteRowsAtIndexPaths:<#(nonnull NSArray<NSIndexPath *> *)#> withRowAnimation:<#(UITableViewRowAnimation)#>]
            //[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
            [NetworkAPI deleteConstructionSiteTaskWithTaskID:data.ID
                                                     Success:^(HXBaseModel *result) {
                                                         if ([result.code isEqualToString:@"200"]) {
                                                             [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                                                             //[tableView reloadData];
                                                         }
                                                     }
                                                     failure:^(NSError *err) {
                                                         [SVProgressHUD showErrorWithStatus:@"删除失败"];
                                                     }];
        }
        if (_isDelete == NO) {
            UIAlertController * deleteAlertCon = [UIAlertController alertControllerWithTitle:@"提示" message:@"超出可修改时间,无法修改" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * certainBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [tableView reloadData];
            }];
            [deleteAlertCon addAction:certainBtn];
            [self presentViewController:deleteAlertCon animated:YES completion:^{
                
            }];
        }
    }];
    return @[deleteAtion];
}

-(void)isDeleteTaskTime {
    
    //获取网络时间
    [NetworkAPI getServerDateSuccess:^(HXServerDateModel *result) {
        if ([result.code isEqualToString:@"200"]) {
            //_nowNetTime = [NSString stringWithFormat:@"%@",result.ServerDate];
            NSLog(@"网络时间数据==================%@",result.ServerDate);
        }
    } failure:^(NSError *err) {
        [SVProgressHUD showErrorWithStatus:@"获取网络时间失败,请检查网络"];
    }];
    //当前时间秒数
    NSDate* nowDate = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval nowTimeSecond=[nowDate timeIntervalSince1970] * 1000;
    NSString * nowTimeString = [NSString stringWithFormat:@"%.0f",nowTimeSecond];
    //将列表时间转化为Date数据
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate * cellTimeDate = [dateformatter dateFromString:_sendTime];
    //将Date数据转化为星期几
    //将列表时间转化为秒数 将秒转化为毫秒 *1000
    NSTimeInterval oneDay = 24*60*60*1; //1天的长度
    NSTimeInterval NowSecond=[cellTimeDate timeIntervalSince1970] * 1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", NowSecond];
    
    NSInteger dis = 1; //前后的天数
    if (([timeString integerValue] + (dis * oneDay * 1000)) >= [nowTimeString integerValue]) {
        self.isDelete = YES;
    }
    else {
        self.isDelete = NO;
    }
}














@end
